package at.ttasat;

import java.io.File;
import java.util.Arrays;

public class Compare {

	public static void main(String[] args) throws Exception {
		if (args.length == 0) {
			System.out.println("Compare [--save[=<filename>] [--noOverwrite]] <comparisonFile> <tasat-Type t/p/l> <parameters for tastat>");
			return;
		}
		String fileName = "results/<c>_<d>.perf";
		boolean save = false;
		boolean noOverwrite = false;
		int index = 0;
		boolean wasUsed;
		do {
			wasUsed = true;
			if (args[index].equals("--save")) {
				save = true;
			} else if (args[index].startsWith("--save=")) {
				save = true;
				fileName = args[index].split("=")[1];
			} else if (args[index].equals("--noOverwrite")) {
				noOverwrite = true;
			} else {
				wasUsed = false;
			}
			if (wasUsed) {
				index++;
			}
			if (args.length < index + 1) {
				throw new IllegalArgumentException();
			}
		} while (wasUsed);

		String comparisonFileName = args[index];
		TasatType type = Util.getTasatType(args[index + 1]);
		String[] parameters = Arrays.copyOfRange(args, index + 2, args.length);
		SolverTestResult comparisonResult = Util.readTestResult(comparisonFileName);
		if (save && noOverwrite) {
			SolverTestResult expectedResult = new SolverTestResult(type, parameters, comparisonResult.getRuns(), comparisonResult.getStartSeed(), null, comparisonResult.getMaximalVariables(),
					comparisonResult.getMaximalClauses(), comparisonResult.getWeightingFactor());
			File expectedFile = new File(Util.getFileName(expectedResult, fileName));
			if (expectedFile.exists()) {
				System.out.println("File '" + expectedFile.getAbsolutePath() + "' already exists");
				return;
			}
		}
		compare(comparisonResult, save, type, parameters, fileName);
	}

	private static void compare(SolverTestResult comparisonResult, boolean save, TasatType type, String[] parameters, String fileName) throws Exception {
		SolverSpeedtest test = new SolverSpeedtest(type, parameters, comparisonResult);
		SolverTestResult result = test.test();
		if (save) {
			Util.save(result, fileName);
		}
		result.printResults();
		System.out.println();
		System.out.println("Compared to:");
		comparisonResult.printResults();
		System.out.println();
		comparisonResult.printComparison(result);
	}
}
